package br.com.center.loja.services;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;

import br.com.center.loja.data.NamedRepository;
import br.com.center.loja.data.Repository;
import br.com.center.loja.data.RepositoryFactoryJPA;
import br.com.center.loja.data.jpa.JPAConnection;

public class Service<T> implements Serializable {

	private static final long serialVersionUID = 1L;
	
	private Class<T> type;
	private transient EntityManager em;
	
	public Service(Class<T> type) {
		super();
		this.type = type;
	}

	protected EntityManager em(){
		if(em == null){
			em = JPAConnection.createEntityManager();
		}
		
		return em;
	}
	
	public List<T> all(){
		Repository<T> repository = 
				RepositoryFactoryJPA.create(type);
		
		return repository.all();
	}
	
	public T get(String name){
		NamedRepository<T> repository = 
				RepositoryFactoryJPA.createNamed(type);
		
		return repository.select(name);
	}

	public T get(Long code){
		Repository<T> repository = 
				RepositoryFactoryJPA.create(type);
		
		return repository.select(code);
	}
	
	public List<T> like(String name){
		NamedRepository<T> repository = 
				RepositoryFactoryJPA.createNamed(type);
		
		return repository.all(name + "%");
	}
}